<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/26
 * Time: 19:36
 */

namespace app\admin\controller;


use app\admin\model\ApiResponse;
use app\admin\lib\AdminController;
use app\common\model\app\AppStartPage;
use app\common\utils\OssUtil;
use think\Db;

class StartPage extends AdminController
{
    /**
     * @return mixed
     */
    public function list() {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
        ]);

        $re = Db::table('app_start_page')
            ->paginate($form['rows']??10, false, [
                'page' => $form['page']??1,
            ])
            ->toArray();
        $re['code'] = 200;

        return $re;
    }

    public function save() {
        $rule = [
            ['image', 'require|url',],
            ['link_url', 'url',],
            ['rank', 'integer',],
        ];
        $form = $this->getAndCheckForm($rule);

        if (isset($form['id'])) {
            $model = AppStartPage::get($form['id']);
            if (empty($model)) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'错误的id');
            OssUtil::delete($model->image);
            AppStartPage::update($form);
        } else {
            AppStartPage::create($form);
        }

        return ApiResponse::success();
    }

    public function toggle_show() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['hide', 'require|integer',],
        ]);

        $id = intval($form['id']);
        $hide = intval($form['hide']);

        AppStartPage::toggleShow($id, $hide);

        return ApiResponse::success();
    }

    public function del() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
        ]);

        $model = AppStartPage::get($form['id']);
        OssUtil::delete($model->image);
        AppStartPage::destroy($model->id);

        return ApiResponse::success();
    }

}